package com.cindata

import com.cindata.dictionary.*
import com.cindata.dimension.RiskDimension
import grails.gorm.transactions.Transactional
import org.springframework.security.access.annotation.Secured

import static org.springframework.http.HttpStatus.*

@Secured(['isAuthenticated()'])
@Transactional
class WorkflowInstanceController {

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def workflowInstanceService
    def springSecurityService

    def index()
    {
    }

    def show(WorkflowInstance workflowInstance) 
    {
        def workflowInstanceStages = WorkflowInstanceStage.findAll("from WorkflowInstanceStage where instance.id = ${workflowInstance?.id} order by executionSequence asc")
        respond workflowInstance, model: [workflowInstanceStages: workflowInstanceStages]
    }

    def create() 
    {
        params.targetUri = request.getHeader("referer")
        respond new WorkflowInstance(params)
    }

    @Transactional
    def save(WorkflowInstance workflowInstance) 
    {
        if (workflowInstance == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }
        if (workflowInstance.hasErrors()) {
            transactionStatus.setRollbackOnly()
            respond workflowInstance.errors, view:'create'
            return
        }
        if (workflowInstance.validate())
        {
            workflowInstance.save flush:true

        }
        else
        {
            println workflowInstance.errors
        }
        workflowInstanceService.initWorkflowInstance(workflowInstance)

        if(workflowInstance?.account){
            redirect controller: "account", action: "accountPendingShow", params:[id:workflowInstance?.id]
            return
        }
        if(workflowInstance?.abnormalMortgageBatch){
            redirect controller: "abnormalMortgageBatch", action: "pendingShow", params:[id:workflowInstance?.id]
            return
        }

        redirect uri: params["targetUri"]

    }

    def edit(WorkflowInstance workflowInstance) 
    {
        params.targetUri = request.getHeader("referer")
        respond workflowInstance
    }

    @Transactional
    def update(WorkflowInstance workflowInstance) 
    {
        if (workflowInstance == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (workflowInstance.hasErrors()) {
            transactionStatus.setRollbackOnly()
            respond workflowInstance.errors, view:'edit'
            return
        }

        workflowInstance.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'workflowInstance.label', default: 'WorkflowInstance'), workflowInstance.id])
                redirect uri: params["targetUri"]
            }
            '*'{ respond workflowInstance, [status: OK] }
        }
    }

    @Transactional
    def delete(WorkflowInstance workflowInstance) {

        if (workflowInstance == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        workflowInstance.delete flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'workflowInstance.label', default: 'WorkflowInstance'), workflowInstance.id])
                redirect action:"index", method:"GET"
            }
            '*'{ render status: NO_CONTENT }
        }
    }

    protected void notFound() {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'workflowInstance.label', default: 'WorkflowInstance'), params.id])
                redirect action: "index", method: "GET"
            }
            '*'{ render status: NOT_FOUND }
        }
    }

    @Transactional
    def approve(WorkflowInstance workflowInstance)
    {
        def targetUri = request.getHeader("referer")
        def classType = params['classType']
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)

        def stage = workflowInstance?.stage
        def map = [:]

        def authority = WorkflowAuthority.findByName("Approval")
        def workflowInstanceUser = WorkflowInstanceUser.findByStageAndUserAndAuthority(stage, user, authority)
        if (workflowInstanceUser)
        {
            map = workflowInstanceService.approve(workflowInstance, classType)
            if (map['flag'])
            {
                stage = workflowInstance?.stage
                def operator = ""
                def workflowInstanceUsers = WorkflowInstanceUser.findAllByStage(stage)
                workflowInstanceUsers?.each {
                    operator += it?.user?.toString() + ","
                }
                if (workflowInstanceUsers?.size() > 0)
                {
                    operator = operator[0..operator.length() - 2]
                }
                flash.message = "已提交至${workflowInstance?.stage?.name}(${operator})"
                redirect url: targetUri
                return
            } 
            else
            {
                def message = map['message']
                if (message)
                {
                    flash.message = map['message']
                } else
                {
                    flash.message = "校验失败"
                }
                redirect url: targetUri
                return
            }
        } 
        else
        {
            flash.message = message(code: '对不起，您没有权限！')
            redirect url: targetUri
            return
        }
    }

    @Transactional
    def reject(WorkflowInstance workflowInstance)
    {
        def targetUri = request.getHeader("referer")
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def stage = workflowInstance?.stage
        def authority = WorkflowAuthority.findByName("Approval")
        def workflowInstanceUser = WorkflowInstanceUser.findByStageAndUserAndAuthority(stage, user, authority)
        def flag

        if (workflowInstanceUser)
        {
            flag = workflowInstanceService.reject(workflowInstance)
            if (flag)
            {
                flash.message = "回退操作成功！"
            } else
            {
                flash.message = message(code: '回退操作失败！')
            }
        } else
        {
            flash.message = message(code: '对不起，您没有权限！')
        }
        redirect url: targetUri
        return
    }

    @Transactional
    def cancel(WorkflowInstance workflowInstance)
    {
        def targetUri = request.getHeader("referer")
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def stage = workflowInstance?.stage
        def authority = WorkflowAuthority.findByName("Approval")
        def workflowInstanceUser = WorkflowInstanceUser.findByStageAndUserAndAuthority(stage, user, authority)
        def flag
        if (workflowInstanceUser)
        {
            flag = workflowInstanceService.cancel(workflowInstance)
            if (flag)
            {
                flash.message = "取消操作成功！"
            } 
            else
            {
                flash.message = message(code: '取消操作失败！')
            }
        } 
        else
        {
            flash.message = message(code: '对不起，您没有权限！')
        }
        redirect url: targetUri
        return
    }

    @Transactional
    def complete(WorkflowInstance workflowInstance)
    {
        def targetUri = request.getHeader("referer")
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def stage = workflowInstance?.stage
        def authority = WorkflowAuthority.findByName("Approval")
        def workflowInstanceUser = WorkflowInstanceUser.findByStageAndUserAndAuthority(stage, user, authority)
        def flag
        if (workflowInstanceUser)
        {
            flag = workflowInstanceService.complete(workflowInstance)
            if (flag)
            {
                flash.message = "结束操作成功！"
            } 
            else
            {
                flash.message = message(code: '结束操作失败！')
            }
        } else
        {
            flash.message = message(code: '对不起，您没有权限！')
        }
        redirect url: targetUri
        return
    }

    def collateralWorkflowInstance()
    {
        def curUser = User.findById(springSecurityService.principal.id)
        def max = params.max ? params.max.toInteger() : 10
        def offset = params.offset ? params.offset.toInteger() : 0
        def externalId = params["externalId"]
        def workflow = params["workflow"]
        def createBy = params["createBy"]
        def status = params["status"]

        def sql = " from WorkflowInstance w where w.collateral.id is not null and w.collateral.account.id = ${curUser?.account?.id}"
        def querySql = " "
        if(externalId)
        {
            querySql += " and w.collateral.externalId like '%${externalId}%' "
        }
        if(workflow)
        {
            querySql += " and w.workflow.id = ${workflow}"
        }
        if (createBy)
        {
            querySql += " and w.createBy.id = ${createBy}"
        }
        if(status)
        {
            querySql += " and w.status.id = ${status}"
        }
        def countSql = "select count(w.id) " + sql
        sql += querySql + " order by w.modifiedDate desc "
        def workflowInstanceList = WorkflowInstance.executeQuery(sql, [max: max, offset: offset])
        def workflowInstanceList1 = WorkflowInstance.executeQuery(countSql)
        respond workflowInstanceList, model: [workflowInstanceCount: workflowInstanceList1[0]]
    }

    def riskWarningWorkflowInstance()
    {
        def curUser = User.findById(springSecurityService.principal.id)
        def max = params.max ? params.max.toInteger() : 10
        def offset = params.offset ? params.offset.toInteger() : 0
        def serialNumber = params["serialNumber"]
        def workflow = params["workflow"]
        def createBy = params["createBy"]
        def status = params["status"]

        def sql = " from WorkflowInstance w where w.riskWarning.id is not null and w.riskWarning.bankAccount.id = ${curUser?.account?.id}"
        def querySql = " "
        if(serialNumber)
        {
            querySql += " and w.riskWarning.serialNumber like '%${serialNumber}%' "
        }
        if(workflow)
        {
            querySql += " and w.workflow.id = ${workflow}"
        }
        if (createBy)
        {
            querySql += " and w.createBy.id = ${createBy}"
        }
        if(status)
        {
            querySql += " and w.status.id = ${status}"
        }
        def countSql = "select count(w.id) " + sql
        sql += querySql + " order by w.modifiedDate desc "

        def workflowInstanceList = WorkflowInstance.executeQuery(sql, [max: max, offset: offset])
        def workflowInstanceList1 = WorkflowInstance.executeQuery(countSql)
        respond workflowInstanceList, model: [workflowInstanceCount: workflowInstanceList1[0]]
    }

    def abnormalMortgageWorkflowInstance()
    {
        def curUser = User.findById(springSecurityService.principal.id)
        def max = params.max ? params.max.toInteger() : 10
        def offset = params.offset ? params.offset.toInteger() : 0
        def name = params["name"]
        def workflow = params["workflow"]
        def createBy = params["createBy"]
        def status = params["status"]

        def sql = " from WorkflowInstance w where w.abnormalMortgageBatch.id is not null and w.abnormalMortgageBatch.account.id = ${curUser?.account?.id} "
        def querySql = " "
        if(name)
        {
            querySql += " and w.abnormalMortgageBatch.name like '%${name}%' "
        }
        if(workflow)
        {
            querySql += " and w.abnormalMortgageBatch.workflow.id = ${workflow}"
        }
        if (createBy)
        {
            querySql += " and w.createBy.id = ${createBy}"
        }
        if(status)
        {
            querySql += " and w.status.id = ${status}"
        }
        def countSql = "select count(w.id) " + sql
        sql += querySql + " order by w.modifiedDate desc "

        def workflowInstanceList = WorkflowInstance.executeQuery(sql, [max: max, offset: offset])
        def workflowInstanceList1 = WorkflowInstance.executeQuery(countSql)
        respond workflowInstanceList, model: [workflowInstanceCount: workflowInstanceList1[0]]
    }

    def accountWorkflowInstance()
    {
        def curUser = User.findById(springSecurityService.principal.id)
        def max = params.max ? params.max.toInteger() : 10
        def offset = params.offset ? params.offset.toInteger() : 0
        def name = params["name"]
        def workflow = params["workflow"]
        def createBy = params["createBy"]
        def status = params["status"]

        def sql = " from WorkflowInstance w where w.account.id is not null and w.account.bankAccount.id = ${curUser?.account?.id}"
        def querySql = " "
        if(name)
        {
            querySql += " and w.account.name like '%${name}%' "
        }
        if(workflow)
        {
            querySql += " and w.workflow.id = ${workflow}"
        }
        if (createBy) 
        {
            querySql += " and w.createBy.id = ${createBy}"    
        }
        if(status)
        {
            querySql += " and w.status.id = ${status}"
        }
        def countSql = "select count(w.id) " + sql
        sql += querySql + " order by w.modifiedDate desc "

        def workflowInstanceList = WorkflowInstance.executeQuery(sql, [max: max, offset: offset])
        def workflowInstanceList1 = WorkflowInstance.executeQuery(countSql)
        respond workflowInstanceList, model: [workflowInstanceCount: workflowInstanceList1[0]]
    }
}
